﻿using System.Windows;
using System.Windows.Media;

namespace Songhay.Extensions
{
    /// <summary>
    /// Extensions for <see cref="System.Windows.DependencyObject"/>.
    /// </summary>
    public static class DependencyObjectExtensions
    {
        /// <summary>
        /// Walk up the VisualTree, returning first parent object of the type supplied as type parameter
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">The obj.</param>
        /// <remarks>
        /// For more, see “Expand/Collapse button in a Silverlight DataGrid”
        /// [http://stackoverflow.com/questions/5232683/expand-collapse-button-in-a-silverlight-datagrid]
        /// </remarks>
        public static T FindAncestor<T>(this DependencyObject obj) where T : DependencyObject
        {
            while(obj != null)
            {
                T o = obj as T;
                if(o != null)
                    return o;

                obj = VisualTreeHelper.GetParent(obj);
            }
            return null;
        }
    }
}
